﻿namespace CodeSmackdown.Web.Models
{
    using System.Linq;

    public class SnippetModel
    {
        public Snippet Snippet
        {
            get;
            private set;
        }

        public int VoteCountSnippet1
        {
            get;
            private set;
        }

        public int VoteCountSnippet2
        {
            get;
            private set;
        }

        public int TotalVotes
        {
            get;
            private set;
        }

        public bool CurrentUserVoted
        {
            get;
            private set;
        }

        /// <summary>
        /// If null, no vote, otherwise indication of which item was voted.
        /// </summary>
        public bool? CurrentUserVotedSnippet1
        {
            get;
            private set;
        }

        public SnippetModel(Snippet snippet, User currentUser)
        {
            this.Snippet = snippet;
            this.TotalVotes = this.Snippet.Votes.Count;
            this.VoteCountSnippet1 = (from v in this.Snippet.Votes
                                      where v.VoteForSnippet1.HasValue && v.VoteForSnippet1.Value
                                      select v).Count();

            this.VoteCountSnippet2 = (from v in this.Snippet.Votes
                                      where v.VoteForSnippet1.HasValue && !v.VoteForSnippet1.Value
                                      select v).Count();

            if (currentUser != null)
            {
                // determine if the current user has voted
                var votes = (from v in this.Snippet.Votes
                             where v.UserID == currentUser.UserID
                             select v);

                if (votes.Count() > 0)
                {
                    this.CurrentUserVoted = true;
                    // vote found, stored who they voted for.
                    this.CurrentUserVotedSnippet1 = votes.First().VoteForSnippet1;
                }
                else
                {
                    this.CurrentUserVoted = false;
                }
            }
        }
    }
}
